<template>
  <div class="projectArchiveConfig-container page-common-layout">
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <AssociativeSelectGroup
            :map="selectMap"
            @conditionChange="selectGroupChange($event)"
            :key="key"
          >
            <template slot="space_1">
              <a-input
                placeholder="请输入标准名称"
                allowClear
                v-model.trim="standardName"
              >
              </a-input>
            </template>
          </AssociativeSelectGroup>
        </template>
        <template slot="operate">
          <a-button class="cu-btn-primary" icon="search" @click="search()">
            查询
          </a-button>
          <a-button class="cu-btn-filter" icon="reload" @click="reset()">
            重置
          </a-button>
        </template>
      </ScreenConditions>
    </div>
    <div class="config-body-container">
      <div class="operate">
        <a-button
          @click="handleAdd()"
          class="cu-btn-primary margin-bottom-xs"
          icon="plus"
          v-action:gcdapz_add
        >
          新增
        </a-button>
      </div>
      <div class="main">
        <vxe-table
          ref="xTable"
          height="99%"
          align="center"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
        >
          <vxe-column type="seq" width="80" title="序号"></vxe-column>
          <vxe-column field="proName" title="项目名称"> </vxe-column>
          <vxe-column field="standardName" title="标准名称"> </vxe-column>
          <vxe-column field="creator" title="创建人"> </vxe-column>
          <vxe-column field="createTime" title="创建时间"> </vxe-column>
          <vxe-column
            field="operate"
            width="120"
            title="操作"
            fixed="right"
            align="left"
          >
            <template #default="{ row }">
              <div class="text-button-group">
                <a-tooltip>
                  <template slot="title">
                    查看
                  </template>
                  <a-icon type="file-search" @click="gotoDetail(row)" />
                </a-tooltip>
                <a-tooltip v-action:gcdapz_edit>
                  <template slot="title">
                    编辑
                  </template>
                  <a-icon type="edit" @click="editor(row)" />
                </a-tooltip>
                <a-tooltip v-action:gcdapz_delete>
                  <template slot="title">
                    删除
                  </template>
                  <a-icon type="delete" @click="handleDelClick(row)" />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="pager-container">
        <vxe-pager
          size="small"
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
          :page-sizes="[20, 50, 100, 500]"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              共<span>{{ pager.total }}</span
              >条
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>
    <!-- 编辑-->
    <edit-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :url="url"
      requestMethod="post"
      :tableDataType="tableDataType"
      @cancel="handleCancel()"
      @ok="handleOk()"
    />
    <!-- 详情 -->
    <detailPage
      :key="detailPage.key"
      :visible.sync="detailPage.visible"
      :uuid="detailPage.uuid"
      :proCode="detailPage.proCode"
    ></detailPage>
  </div>
</template>

<script>
//项目档案配置
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
import AssociativeSelectGroup from "@/components/extendCustom/AssociativeSelectGroup";
//编辑
import editForm from "@/pages/form/formPreview/edit.vue";
//详情
import detailPage from "./components/detailPage.vue";
import { pageArchiveConfig, deleteArchiveConfig } from "@/api/safetyManage";
export default {
  components: {
    ScreenConditions,
    AssociativeSelectGroup,
    editForm,
    detailPage,
  },
  data() {
    return {
      key: "page",
      selectMap: [
        //项目
        {
          type: "proCode",
          mode: "default",
          placeholder: "请选择项目",
          allowClear: true,
        },
      ],
      conditionsData: {},
      //标准名称
      standardName: "",
      //列表
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      //编辑
      visible: false,
      confirmLoading: false,
      url: {
        save: "/form/formDatabase/formSave",
        update: "/form/formDatabase/formUpdate",
      },
      tableDataType: "",
      tableUuid: "6B46631F1F064AD4BC6E174FAC72D27F",
      modalFooter: {},
      //详情
      detailPage: {
        key: "detail",
        visible: false,
        proCode: "",
        uuid: "",
      },
    };
  },
  methods: {
    //关闭弹窗
    handleCancel() {
      this.visible = false;
    },
    handleOk() {
      this.visible = false;
      this.getTableData();
    },
    // 新增
    async handleAdd() {
      this.modalFooter = {};
      this.visible = true;
      this.$refs.createModal.title = "新增";
      let formJsonData = await this.loadDataJson(this.tableUuid);
      let { addApiUrl } = JSON.parse(formJsonData)?.config ?? {};
      this.url.save = addApiUrl ?? "/form/formDatabase/formSave";
      this.$refs.createModal.loadData(this.tableUuid, "add", formJsonData);
    },
    //编辑
    async editor(record = {}) {
      let { uuid } = record;
      this.visible = true;
      let formJsonData = await this.loadDataJson(this.tableUuid);
      let { editApiUrl } = JSON.parse(formJsonData)?.config ?? {};
      this.url.update = editApiUrl ?? "/form/formDatabase/formSave";
      this.$refs.createModal.title = "编辑";
      this.$refs.createModal.loading = true;
      this.$post("/form/formDatabase/formGetDetail", {
        uuid: uuid,
        formUuid: this.tableUuid,
      }).then((res) => {
        this.$refs.createModal.loadData(
          this.tableUuid,
          "edit",
          formJsonData,
          res
        );
      });
    },

    loadDataJson(tableUuid = "") {
      return new Promise((reslove) => {
        this.$post("/form/formBasicConfigure/getDetailByUuid", {
          uuid: tableUuid,
        })
          .then((res) => {
            this.tableDataType = res.formDatabase?.type || "";
            reslove(res.formDesign.designJson);
          })
          .catch((_) => {
            reslove({});
          });
      });
    },
    //删除
    handleDelClick(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          deleteArchiveConfig({ uuid: row.uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //详情
    gotoDetail(row) {
      this.detailPage.key = Date.now();
      this.detailPage.proCode = row.proCode;
      this.detailPage.uuid = row.uuid;
      this.detailPage.visible = true;
    },
    search() {
      this.pager.page = 1;
      this.getTableData();
    },
    reset() {
      this.standardName = "";
      this.key = Date.now();
    },
    selectGroupChange(data) {
      this.dealConditionsData(data);
      this.pager.page = 1;
      this.getTableData();
    },

    //处理搜索区域选中值
    dealConditionsData(data = {}) {
      Object.keys(data).forEach((key) => {
        if (!data[key]) {
          this.conditionsData[key] = "";
        } else if (Array.isArray(data[key])) {
          this.conditionsData[key] = data[key]
            .map((v) => v.key)
            .filter((v) => v)
            .toString();
        } else if (
          Object.prototype.toString.call(data[key]) === "[object Object]"
        ) {
          this.conditionsData[key] = data[key].key;
        } else {
          this.conditionsData[key] = "";
        }
      });
    },

    //查询分页数据
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let { proCode } = this.conditionsData;
      let { standardName } = this;
      pageArchiveConfig({
        page,
        pageSize,
        proCode,
        standardName,
      })
        .then((res) => {
          this.tableData = res?.data?.rows || [];
          this.pager.total = res?.data?.totalCount || 0;
        })
        .catch((_) => {
          this.tableData = [];
          this.pager.total = 0;
        })
        .finally((_) => {
          this.loading = false;
        });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },
  },
};
</script>

<style lang="less" scoped>
.projectArchiveConfig-container {
  display: flex;
  flex-direction: column;
  .config-body-container {
    flex: 1;
    background-color: @base-bg-color;
    flex-shrink: 0;
    position: relative;
    padding: 10px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    .operate {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .main {
      flex: 1;
    }
    .pager-container {
      flex-shrink: 0;
      box-sizing: border-box;
    }
  }
}
</style>
